import utils from './utils';
import logger from './logger';
import fs from '@ohos.file.fs';
import inter_installer from '@ohos.bundle.installer';
import settingHelper from '../manager/settingHelper';
import bundleManager from '@ohos.bundle.bundleManager';

class installer {
  getBundleInfo(packageName: string): Promise<bundleManager.BundleInfo> {
    return new Promise((resolve) => {
      try {
        let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE |
        bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY;
        bundleManager.getBundleInfo(packageName, bundleFlags, 100).then((data) => resolve(data))
          .catch((err) => {
            logger.error(err);
            resolve(null);
          });
      } catch (e) {
        logger.error(e);
        resolve(null);
      }
    });
  }

  install(hapFile: string): Promise<string> {
    return new Promise((resolve) => {
      inter_installer.getBundleInstaller().then(data => {
        let installParam = {
          userId: 100,
          installFlag: 1,
          isKeepData: false
        };
        data.install([hapFile], installParam, err => {
          if (err) {
            logger.error(err);
            resolve(err.message);
          } else {
            resolve(null);
            if (settingHelper.autoDelete)
              fs.unlink(hapFile);
          }
        });
      }).catch(err => {
        logger.error(err);
        resolve(err.message);
      });
    });
  }

  run(bundleName: string): Promise<boolean> {
    return new Promise((resolve) => {
      let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE |
      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY;
      let userId = 100;
      bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => {
        if (err) {
          logger.error(err);
          utils.showPopup(`应用不存在`);
          resolve(false);
        } else {
          let entryAbilityName = data.hapModulesInfo[0].mainElementName;
          globalThis.abilityContext.startAbility({
            moduleName: '',
            bundleName: bundleName,
            abilityName: entryAbilityName
          }).then(() => resolve(true))
            .catch((err) => {
              logger.error(err);
              resolve(false);
              utils.showPopup(`应用不存在`);
            });
        }
      });
    });
  }

  reset(bundleName: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        let installParam = {
          userId: 100,
          isKeepData: false,
          installFlag: 1,
        };
        inter_installer.getBundleInstaller().then(data => {
          data.recover(bundleName, installParam)
            .then(() => resolve(true))
            .catch(err => {
              logger.error(err);
              resolve(false);
            });
        }).catch(err => {
          logger.error(err);
          resolve(false);
        });
      } catch (error) {
        logger.error(error);
        resolve(false);
      }
    });
  }

  uninstall(bundleName: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        let installParam = {
          userId: 100,
          installFlag: 1,
          isKeepData: false
        };
        inter_installer.getBundleInstaller().then(data => {
          data.uninstall(bundleName, installParam)
            .then(() => resolve(true))
            .catch((err) => {
              logger.error(err);
              resolve(false);
            })
        }).catch(err => {
          logger.error(err);
          resolve(false);
        });
      } catch (error) {
        logger.error(error);
        resolve(false);
      }
    });
  }

  clearAppCache(bundleName: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        bundleManager.cleanBundleCacheFiles(bundleName)
          .then(() => resolve(true))
          .catch(err => {
            logger.error(err);
            resolve(false);
          });
      } catch (error) {
        logger.error(error);
      }
    });
  }

  setAppState(bundleName: string, state: boolean): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        bundleManager.setApplicationEnabled(bundleName, state)
          .then(() => resolve(true))
          .catch(err => {
            logger.error(err);
            resolve(false);
          });
      } catch (error) {
        logger.error(error);
        resolve(false);
      }
    });
  }
}
export default new installer();